export const DEFAULT_VALUE = {
  ARRAY: "[]",
  OBJECT: "{}",
  STRING: "",
};

interface ILocalStorageFactoryParams<T> {
  key: string;
  defaultValue: string;
  raw?: boolean;
  serializer?: (value: T) => string;
  deserializer?: (value: string) => T;
}

interface ILocalStorageFactoryReturn<T> {
  setItem: (value: T) => void;
  getItem: () => T;
  removeItem: () => void;
}

export const localStorageFactory = <T>(
  params: ILocalStorageFactoryParams<T>
): ILocalStorageFactoryReturn<T> => {
  const {
    key,
    defaultValue,
    raw,
    serializer = JSON.stringify,
    deserializer = JSON.parse,
  } = params;

  const setItem = (value: T) => {
    const data = (raw ? value : serializer(value)) as string;
    window.localStorage.setItem(key, data || defaultValue);
  };

  const getItem = () => {
    const data = window.localStorage.getItem(key) || defaultValue;
    return raw ? data : deserializer(data);
  };

  const removeItem = () => window.localStorage.removeItem(key);

  return {
    setItem,
    getItem,
    removeItem,
  };
};

export const setlocalStorage = (dataName: string, data: Array<string>) => {
  return window.localStorage.setItem(dataName, JSON.stringify(data));
};

export const getlocalStorage = (dataName: string) => {
  if (window.localStorage.getItem(dataName)) {
    return JSON.parse(window.localStorage.getItem(dataName) || "");
  } else {
    return [];
  }
};

// 设置播放历史
export const setPlayHistory = (music) => {
  const list = getlocalStorage("playHistory");
  if (list && list.length) {
    const temp = list.filter((it) => it.musicId !== music.musicId);
    temp.push(music);
    window.localStorage.setItem("playHistory", JSON.stringify(temp));
  } else {
    window.localStorage.setItem("playHistory", JSON.stringify([music]));
  }
};

// 添加收藏歌单
export const addCollect = (songSheet) => {
  const list = getlocalStorage("CollectSongSheet");
  if (list && list.length) {
    const temp = list.filter((it) => it.id == songSheet.id); // 防止重复收藏

    if (temp.length) {
      return;
    }

    window.localStorage.setItem(
      "CollectSongSheet",
      JSON.stringify(list.push(songSheet))
    );
  } else {
    window.localStorage.setItem(
      "CollectSongSheet",
      JSON.stringify([songSheet])
    );
  }
};
